#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011 BidiX (http://bidix.info)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
"""
	Wrapper for django template in GAE
	
	Notewiki filters added to django templates :
		- :func:`truncatechars`
		- :func:`ltruncatechars`
		- 'func:`notewiki.ui.dehtml`
		
"""
import os
import logging
import datetime

import config
from notewiki.model import Article, current_wikiname
from notewiki.ui import dehtml

from django.conf import settings
from django.template import TemplateDoesNotExist, Context
from django.template.loader import BaseLoader
import django.template.loader

import webapp2

class WikiLoader(BaseLoader):
	"""
 		Loader for loading templates from Notewiki 
		with a fall-back to file

		add in django settings : 
		TEMPLATE_LOADERS=[('notewiki.ui.template.WikiLoader',)]

	"""
	is_usable = True
	
	def load_file_template_source(self, template_name):
		"""
		Load template from static file in *file_template_root_path*
		"""
		config = webapp2.get_app().config
		file_path = config.get('file_template_root_path') + '/' + template_name + '.djhtml'
		try:
			file = open(file_path)
			try:
				return (file.read().decode(config.get('file_charset')), file_path)
			finally:
				file.close()
		except IOError:
			error_msg = "Template file %s not found"%file_path
			logging.error(error_msg)
			raise TemplateDoesNotExist(error_msg)

	def load_personal_wiki_template_source(self, template_name):
		"""
		Load template_name from article in wiki with _{user_wikiname} as personal_folder
		"""
		personal_folder = current_wikiname()
		if personal_folder:
			personal_folder = '_'+personal_folder
		return self.load_wiki_template_source(template_name, personal_folder)
			

	def load_wiki_template_source(self, template_name, personal_folder=''):
		"""
		Load template from wiki.
		
		If personal_folder
			try to load from {personal_folder}/{template_name}
		else
			{template_name}
		"""
		config = webapp2.get_app().config
		wiki_template_root_folder = config.get('wiki_template_root_folder')
		if personal_folder:
			personal_folder = personal_folder + '/'
		else:
			personal_folder = ''
		personal_article = Article.get_by_name(personal_folder+wiki_template_root_folder+'/'+template_name)
		article = Article.get_by_name(wiki_template_root_folder+'/'+template_name)
		if personal_article:
			logging.debug("Render with article %s"%personal_folder+wiki_template_root_folder+'/'+template_name)
			return (personal_article.text, template_name)
		elif article:
			logging.debug("Render with article %s"%wiki_template_root_folder+'/'+template_name)
			return (article.text, template_name)
		else:
			return(self.load_file_template_source(template_name))
			
	def load_template_source(self, template_name, template_dirs=None):
		"""
		Depending on configuration, load template from :
		- *personal_wiki_template_support*: personal area in notewiki 
		- *wiki_template_support*: public wiki area in notewiki 
		- from static file 
		"""
		if webapp2.get_app().config.get('personal_wiki_template_support'):
			return self.load_personal_wiki_template_source(template_name)
		elif webapp2.get_app().config.get('wiki_template_support'):
			return self.load_wiki_template_source(template_name)
		else:
			return self.load_file_template_source(template_name)
		
	load_template_source.is_usable = True

def truncatechars(str, maxlength=10):
	"""
	Django template filter : truncate maxlength chars
	"""
	m = int(maxlength)
	if len(str) <= m:
		return str
	else:
		return str[0:m-4]+'...'
	
def ltruncatechars(str, maxlength=10):
	"""
	Django template filter : left truncate maxlength chars
	"""
	m = int(maxlength)
	if len(str) <= m:
		return str
	else:
		return '...'+str[(len(str)-m)+4:]

django.template.defaultfilters.register.filter('truncatechars', truncatechars)
django.template.defaultfilters.register.filter('ltruncatechars', ltruncatechars)
django.template.defaultfilters.register.filter('dehtml', dehtml)

def render(template_path, template_context, debug=False):
	"""
	Render, using Django, template_context using template_path.
	
	Add user_agent in context with :
	- iphone
	- ipad
	- other
	"""
	os.environ['DJANGO_SETTINGS_MODULE'] = 'notewiki.ui.django_settings'
	template_context['current_year'] = datetime.datetime.utcnow().strftime('%Y')
	#
	# set user_agent in context
	# iPhone
	# iPad
	# other
	#
	user_agent_header = os.environ['HTTP_USER_AGENT']
	if user_agent_header.find('iPhone') > 0:
		user_agent = 'iPhone'
	elif user_agent_header.find('iPad') > 0:
		user_agent = 'iPad'
	else:
		user_agent = 'other'
	template_context['user_agent'] = user_agent
	if template_context.has_key('title'):
			template_context['html_title'] = dehtml(template_context['title'])
	t, name = django.template.loader.find_template(template_path)
	return t.render(Context(template_context))
